package com.fy.utils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

/**
 * 存放字符串,数字的处理工具类
 */
public class CommonUtils {

	public static final int SIZETYPE_B = 1;//获取文件大小单位为B的double值
	public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值
	public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值
	public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值
	/**
	 * <pre>
	 * CommonUtils.toString(null)         = ""
	 * CommonUtils.toString("")           = ""
	 * CommonUtils.toString("bat")        = "bat"
	 * CommonUtils.toString(Boolean.TRUE) = "true"
	 * </pre>
	 *
	 * @param obj
	 * @return String
	 */
	public static String toString(Object obj) {
		return obj == null ? "" : obj.toString();
	}

	/**
	 * @param obj
	 * @return
	 */
	public static String null2Zero(Object obj) {
		return obj == null || obj.equals("") ? "0" : obj.toString();
	}

	/**
	 * @param obj
	 * @return
	 */
	public static Integer obj2Integer(Object obj) {
		if (!isNumeric(toString(obj).replaceAll("-", ""))) {
			return null;
		}
		return obj == null || obj.equals("") ? 0 : Integer.parseInt(obj.toString());
	}

	/**
	 * @param obj
	 * @return
	 */
	public static Long obj2Long(Object obj) {
		if (!isNumeric(toString(obj))) {
			return null;
		}
		return (obj == null || (obj.toString().equals(""))) ? 0l : Long.parseLong(obj.toString());
	}

	public static BigDecimal obj2BigDecimal(Object obj) {
		if ((obj == null || obj.equals(""))) {
			return new BigDecimal(0);
		}
		Boolean minus = false;
		if (obj.toString().indexOf("-") > 0) {// 负数特殊处理
			minus = true;
		}
		if (!isBigDecimal(toString(obj))) {
			return null;
		}
		BigDecimal ret = new BigDecimal(obj.toString());
		if (minus) {
			ret = BigDecimal.ZERO.subtract(ret);
		}
		return ret;
	}

	// public static BigDecimal obj2BigDecimal(Object obj, int newScale, int
	// roundingMode) {
	// BigDecimal data = obj2BigDecimal(obj);
	// data.setScale(newScale, roundingMode);
	// return data;
	// }

	/**
	 * 判断是否是正浮点型数字
	 *
	 * @param str
	 * @return
	 */
	public static boolean isDecimal(String str) {
		Pattern pattern = Pattern
				.compile("^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	public static boolean isBigDecimal(String str) {
		try {
			BigDecimal bd = new BigDecimal(str);

			// bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * 利用正则表达式判断字符串是否是数字
	 *
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	public static String decimalToBinary(int decimalSource) {
		BigInteger bi = new BigInteger(String.valueOf(decimalSource)); // 转换成BigInteger类型
		return bi.toString(2); // 参数2指定的是转化成X进制，默认10进制
	}

	/**
	 * @Description: 二进制转换成十进制
	 * @param binarySource
	 * @return int
	 */
	public static int binaryToDecimal(String binarySource) {
		BigInteger bi = new BigInteger(binarySource, 2); // 转换为BigInteger类型
		return Integer.parseInt(bi.toString()); // 转换成十进制
	}

	/**
	 * 做幂运算
	 *
	 * @param x
	 * @param n
	 * @return
	 */
	public static long pow(long x, int n) {
		long pow = 1;
		if (n == 0) {
			return 1;
		}
		while (n > 0) {
			if (n % 2 == 1) {
				pow *= x;
			}
			x *= x;
			n >>= 1;
		}
		return pow;
	}

	/**
	 * 对数运算
	 *
	 * @param value
	 * @param base  底数
	 * @return doublel
	 */
	public static Double log(Long value, Long base) {
		return Math.log(value) / Math.log(base);
	}

	/**
	 * 计算总页数
	 *
	 * @param pageSize
	 * @param totalRows
	 * @return
	 */
	public static Integer getTotalPages(Integer pageSize, Integer totalRows) {
		Integer pages = 0;
		if (totalRows == 0) {
			return pages;
		}
		if (totalRows % pageSize == 0) {// 没有余数
			return totalRows / pageSize;
		}
		pages = (totalRows / pageSize) + 1;
		return pages;
	}

	/**
	 * 判断字符串是否包含大写括号
	 *
	 * @param searchStr
	 * @return
	 */
	public boolean containsFullAngle(String searchStr) {
		if (StringUtils.containsAny(searchStr, "（") || StringUtils.containsAny(searchStr, "）")) {
			return true;
		}
		return false;
	}

	/**
	 * 替换字符串里的大写括号
	 *
	 * @param replaceStr
	 * @return
	 */
	public static String convertAngleFulltoHalf(String replaceStr) {
		String search = "（";
		if (StringUtils.containsAny(replaceStr, "（")) {
			replaceStr = StringUtils.replace(replaceStr, search, "(");
		}
		String search2 = "）";
		if (StringUtils.containsAny(replaceStr, search2)) {
			replaceStr = StringUtils.replace(replaceStr, search2, ")");
		}
		return replaceStr;
	}

	/**
	 * 包含有中文字符串,全角转半角
	 *
	 * @param input
	 * @return
	 */
	public static String ToDBC(String input) {
		char c[] = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == '\u3000') {
				c[i] = ' ';
			} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
				c[i] = (char) (c[i] - 65248);
			}
		}
		String returnString = new String(c);
		return returnString;
	}

	/**
	 * 包含有中文字符串,半角转全角
	 *
	 * @param input
	 * @return
	 */
	public static String ToSBC(String input) {
		char c[] = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == ' ') {
				c[i] = '\u3000';
			} else if (c[i] < '\177') {
				c[i] = (char) (c[i] + 65248);
			}
		}
		return new String(c);
	}

	/**
	 * 根据正则表达式判断字符是否为汉字 字符串中包含汉字时返回true
	 */
	public static boolean hasChinese(String value) {
		// 汉字的Unicode取值范围
		String regex = "[\u4e00-\u9fa5]";
		Pattern pattern = Pattern.compile(regex);
		Matcher match = pattern.matcher(value);

		return match.find();
	}

	public static String toMicrometerStr(BigDecimal value) {
		DecimalFormat df = new DecimalFormat("#,##0.####;(#)");
		return df.format(value);
	}

	// 生成随机数字和字母,
	public static String getStringRandom(int length, boolean isNum) {
		String val = "";
		Random random = new Random();
		// 参数length，表示生成几位随机数
		for (int i = 0; i < length; i++) {
			String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
			if (isNum) {
				charOrNum = "num";
			}
			// 输出字母还是数字
			if ("char".equalsIgnoreCase(charOrNum)) {
				// 输出是大写字母还是小写字母
				int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
				val += (char) (random.nextInt(26) + temp);
			} else if ("num".equalsIgnoreCase(charOrNum)) {
				val += String.valueOf(random.nextInt(10));
			}
		}
		return val;
	}

	public static String appendStr(Set<String> set) {
		String result = "";
		Iterator<String> it = set.iterator();
		while (it.hasNext()) {
			String sr = it.next();
			if (!sr.isEmpty()) {
				result += sr + ",";
			}
		}
		if (result.isEmpty()) {
			return result;
		}
		return result.substring(0, result.length() - 1);
	}

	/**
	 * fileSize 文件大小kb
	 * 转换文件大小,指定转换的类型
	 */
	public static String formetFileSize(long fileSize, int sizeType) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeLong = "";
		switch (sizeType) {
			case SIZETYPE_MB:
				fileSizeLong = df.format((double) fileSize / 1024);
				break;
			case SIZETYPE_GB:
				fileSizeLong = df.format((double) fileSize / 1048576);
				break;
			default:
				break;
		}
		return fileSizeLong;
	}

	public static String FormetFileSize(long fileS) {//转换文件大小
		DecimalFormat df = new DecimalFormat("0.00");
		String fileSizeString = "";
		if (fileS < 1024) {
			fileSizeString = fileS + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024);
			String sux = fileSizeString.substring(fileSizeString.indexOf(".") + 1, fileSizeString.length());
			int num = Integer.parseInt(sux);
			if(num == 0){
				fileSizeString = Math.round((double) fileS / 1024) + "KB";
			}else{
				fileSizeString = df.format((double) fileS / 1024) + "KB";
			}

		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576);
			String sux = fileSizeString.substring(fileSizeString.indexOf(".") + 1, fileSizeString.length());
			int num = Integer.parseInt(sux);
			if(num == 0){
				fileSizeString = Math.round(((double) fileS / 1048576)) + "MB";
			}else{
				fileSizeString = df.format((double) fileS / 1048576) + "MB";
			}
		} else {
			fileSizeString = df.format((double) fileS / 1073741824);
			String sux = fileSizeString.substring(fileSizeString.indexOf(".") + 1, fileSizeString.length());
			int num = Integer.parseInt(sux);
			if(num == 0){
				fileSizeString = Math.round(((double) fileS / 1073741824)) + "G";
			}else{
				fileSizeString = df.format((double) fileS / 1073741824) + "G";
			}
		}
		return fileSizeString;
	}

	public static void main(String[] args) {
		String code = CommonUtils.getStringRandom(16, false);
		System.out.print(code);

	}

}
